export default {
  data() {
    return {
      showEditIcon: false,
      // 展示标注input框
      showEditInput: false,
      isAddEdit: true,
      annotateText: '',
      clientX: 0,
      clientY: 0,
      currentMarkId: '',
      markContent: []
    }
  },
  methods: {
    // 设置编辑框的位置
    insetAffix(e, height) {
      this.showEditInput = true
      this.$nextTick(() => {
        const { clientX, clientY } = e
        const annotateDom = this.$refs.annotateRef
        let X = height ? clientX - 180 : clientX
        let top = clientY - annotateDom.offsetHeight
        if (height) {
          top = annotateDom.offsetHeight + clientY - 140
        }
        annotateDom.style.cssText = `
        top: ${top}px; left: ${X - 40}px; z-index: 10`
      })
    },
    addMarkListener(selector) {
      let markBody = document.querySelector(selector)
      markBody.addEventListener('click', e => {
        this.showEditInput = false
        const hasMarked = this.markContent.findIndex(item => item.markId === this.currentMarkId) !== -1
        if (!hasMarked) {
          this.deleteMark()
        }
      })
      markBody.addEventListener('mouseup', e => {
        this.$nextTick(() => {
          this.showEditIcon = true
          let signIconRef = this.$refs.signIcon
          if (signIconRef) {
            signIconRef.style.left = e.clientX + 10 + 'px'
            signIconRef.style.top = e.clientY - 60 + 'px'
            this.clientX = e.clientX
            this.clientY = e.clientY
          }
        })
      })
    },
    // 点击添加标注
    // 1. 实现文本标注， 2. 记录当前标注的文本类名
    markText(e) {
      this.insetAffix(e)
      this.isAddEdit = true
      this.annotateText = ''
      const id = `mark-${new Date().getTime()}`
      const currentMarkClass = 'tk-select ' + id
      // 记录当前的markId 用作移入显示
      this.currentMarkId = id
      this.replaceSelectedStrByEle(currentMarkClass)
    },
    getRange() {
      // 此处的Range类是在 当前路由下的index.vue中通过inject注入的
      var range = new Range(window.document)
      var sel = window.getSelection()
      if (sel && sel.rangeCount) {
        var firstRange = sel.getRangeAt(0)
        var lastRange = sel.getRangeAt(sel.rangeCount - 1)
        range
          .setStart(firstRange.startContainer, firstRange.startOffset)
          .setEnd(lastRange.endContainer, lastRange.endOffset)
      }
      return range
    },
    replaceSelectedStrByEle(className) {
      var range = this.getRange()
      range.applyInlineStyle('span', {
        class: className
      })
      range.select()
    },
    // 删除标注
    deleteMark() {
      const content = this.$refs.questionRef
      const targetNodeList = content.querySelectorAll(`.${this.currentMarkId}`)
      for (let i = 0; i < targetNodeList.length; i++) {
        const targetNode = targetNodeList[i]
        const targetText = targetNode.innerText
        const parentNode = targetNode.parentNode
        // 先插入新节点
        const textNode = document.createTextNode(targetText)
        parentNode.insertBefore(textNode, targetNode)
        // 再删除旧节点
        parentNode.removeChild(targetNode)
      }
      this.showEditInput = false
      // 从数组中删除对应标签
      this.markContent = this.markContent.filter(item => item.markId !== this.currentMarkId)
    },
    // 取消添加标注
    cancelAnnotate() {
      this.showEditInput = false
      this.deleteMark()
    },
    // 确认添加标注
    confirmAnnotate() {
      const isEdit = this.markContent.some(item => item.markId === this.currentMarkId)
      const targetNodeList = document.querySelectorAll(`.${this.currentMarkId}`)
      for (let i = 0; i < targetNodeList.length; i++) {
        const targetNode = targetNodeList[i]
        if (targetNode.className.indexOf('tk-marked') === -1) {
          targetNode.classList.add('tk-marked')
        }
        targetNode.addEventListener('mouseenter', e => {
          const hasMarked = this.markContent.findIndex(item => item.markId === this.currentMarkId) !== -1
          if (!hasMarked) {
            this.deleteMark()
          }
          const targetId = Array.prototype.find.call(e.target.classList, item => {
            if (item.indexOf('mark-') !== -1) return item
          })
          // 每次移入当前标注，需要记录当前ID。用于后续的编辑和删除
          this.currentMarkId = targetId
          this.annotateText = (this.markContent.find(item => item.markId === targetId) || {}).content
          this.isAddEdit = false
          this.insetAffix(e)
        })
        targetNode.addEventListener('mouseleave', e => {
          if (e.toElement.className.indexOf('display-mark-box') === -1) {
            this.showEditInput = false
          }
        })
      }
      if (isEdit) {
        // 表示当前是编辑已有标注
        this.markContent.forEach(item => {
          if (item.markId === this.currentMarkId) {
            item.content = this.annotateText
          }
        })
      } else {
        this.markContent.push({
          markId: this.currentMarkId,
          content: this.annotateText
        })
      }
      this.showEditInput = false
    },
    // 编辑标注
    handleEditMark(e) {
      this.insetAffix(e, this.$refs.annotateRef.offsetHeight)
      this.isAddEdit = true
    }
  },
  mounted() {
    document.addEventListener('selectionchange', () => {
      this.showEditIcon = !!window.getSelection().toString()
    })
  }
}
